package com.ruoyi.yipaiju.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.BizConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.core.domain.entity.XcxUser;
import com.ruoyi.common.core.page.TableDataApi;
import com.ruoyi.common.utils.CurrencyUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.http.HttpRequest;
import com.ruoyi.common.utils.http.HttpRespons;
import com.ruoyi.yipaiju.domain.*;
import com.ruoyi.yipaiju.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 折扣
 */
@RestController
@RequestMapping("/houses")
public class HousesDiscountController extends BaseController {

    @Autowired
    private IDiscountHouseService discountHouseService;
    @Autowired
    private IFavoriteService favoriteService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private IDiscountHouseBookingorderService discountHouseBookingorderService;
    @Autowired
    private IDiscountHouseBookingorderFollowerService discountHouseBookingorderFollowerService;
    @Autowired
    private IDiscountHouseSigningorderService discountHouseSigningorderService;
    @Autowired
    private IHouseUploadingOrderService houseUploadingOrderService;
    @Autowired
    private IXcxUserService xcxUserService;

    /**
     *  折扣房源列表
     * @param discountHouse
     * @return
     */
    @GetMapping("/discount")
    public TableDataApi discount(DiscountHouse discountHouse) {
        startPageApi();
        List<DiscountHouse> discountHouses = discountHouseService.selectDiscountHouseList(discountHouse);
        if (SecurityUtils.getLoginUser() != null){
            discountHouses.forEach(item -> {
                if (StringUtils.isNotEmpty(item.getTagsstr())){
                    item.setTags(item.getTagsstr().split(","));
                }
            });
        }

        return getTableApi(discountHouses);
    }

    /**
     * 直接添加折扣房源， TODO  不知道这里要干啥呀。。。。  蒙b呀。。。
     * @return
     */
    @PostMapping("/discount")
    public ApiResult discountDo() {
        // TODO 不知道这里要干啥   难道是要生成一个折扣房源id吗    太2b了。。。。
        DiscountHouse build = Builder.of(DiscountHouse::new)
                .with(DiscountHouse::setUploadTime, new Date())
                .with(DiscountHouse::setStatus, 1)
                .build();
        discountHouseService.insertDiscountHouse(build);
        return ApiResult.success(build);
    }

    /**
     * 放盘提交
     * @param id
     * @param discountHouse
     * @return
     */
    @PostMapping("/discount/{id}")
    public ApiResult discountAdd(@PathVariable("id") Long id, @RequestBody DiscountHouse discountHouse) {
        // TODO 先按id查询，如果存在则修改
        discountHouse.setId(id);
        if (discountHouse.getTags() != null){
            discountHouse.setTagsstr(StringUtils.join(discountHouse.getTags(), ","));
        }
        // TODO 添加banner字段， 直接把图片存上
        // 从前台送过来一个banner的id 然后去反查下
//        discountHouse.setBanner();
        DiscountHouse discountHouse1 = discountHouseService.selectDiscountHouseById(id);

        try {
            // TODO 根据地址求出地图坐标
            String address = discountHouse.getProvince() + discountHouse.getCity() + discountHouse.getDistrict() + discountHouse.getLocation();
            HttpRequest httpRequest = new HttpRequest();
            HttpRespons httpRespons = httpRequest.sendGet(String.format(BizConstants.GEOCODER_URL, URLEncoder.encode(address, Constants.UTF8)));
            if (httpRespons != null && httpRespons.getCode() == HttpStatus.SUCCESS){
                JSONObject resultJson = JSONObject.parseObject(httpRespons.getContent());
                int status = (int) CurrencyUtil.readJson(resultJson, "status");
                if (status == 0){
                    String lng = String.valueOf(CurrencyUtil.readJson(resultJson, "result.location.lng"));
                    String lat = String.valueOf(CurrencyUtil.readJson(resultJson, "result.location.lat"));
//                String province = String.valueOf(CurrencyUtil.readJson(resultJson, "result.address_components.province"));
//                String city = String.valueOf(CurrencyUtil.readJson(resultJson, "result.address_components.city"));
//                String district = String.valueOf(CurrencyUtil.readJson(resultJson, "result.address_components.district"));
                    discountHouse.setLongitude(lng);
                    discountHouse.setLatitude(lat);
//                discountHouse.setProvince(province);
//                discountHouse.setCity(city);
//                discountHouse.setDistrict(district);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        discountHouse.setUploadTime(new Date());
        if (discountHouse1 == null){
            // 这个好像不用了 应该不会走到插入了
            discountHouseService.insertDiscountHouse(discountHouse);
        }else {
            discountHouseService.updateDiscountHouse(discountHouse);
        }
        return ApiResult.success();
    }

    /**
     * 折扣房源详情
     * @param id
     * @return
     */
    @GetMapping(value = "/discount/{id}")
    public ApiResult discountInfo(@PathVariable("id") Long id)
    {
        DiscountHouse discountHouse = discountHouseService.selectDiscountHouseById(id);
        if (discountHouse != null){
            //获取用户是否收藏
            Favorite favorite = favoriteService.selectOneFavorite(Builder.of(Favorite::new)
                    .with(Favorite::setClient, SecurityUtils.getUserId().toString())
                    .with(Favorite::setDiscountHouseId, id)
                    .build());
            if (favorite == null){
                discountHouse.setIsfavor(0);
            }else {
                discountHouse.setIsfavor(1);
                discountHouse.setFavorId(favorite.getId());
            }
            Notice notice = noticeService.selectOneNotice(Builder.of(Notice::new)
                    .with(Notice::setClient, SecurityUtils.getUserId().toString())
                    .with(Notice::setDiscountHouseId, id)
                    .build());
            if (notice == null){
                discountHouse.setIsnotice(0);
            }else {
                discountHouse.setIsnotice(1);
                discountHouse.setNoticeId(notice.getId());
            }
            return ApiResult.success(discountHouse);
        }else {
            return ApiResult.error("房源不见了...");
        }
    }

    /**
     * 一键预约折扣
     * @param discountHouseBookingorder
     * @return
     */
    @PostMapping("/discount/booking/orders")
    public ApiResult discountBookingOrders(@RequestBody DiscountHouseBookingorder discountHouseBookingorder){
        DiscountHouse discountHouse = discountHouseService.selectDiscountHouseById(discountHouseBookingorder.getDiscountHouseId());
        if (discountHouse != null){
            discountHouseBookingorder.setNo(CurrencyUtil.create(10));
            discountHouseBookingorder.setClient(SecurityUtils.getUserId());
            discountHouseBookingorder.setDiscountHouseTitle(discountHouse.getTitle());
            discountHouseBookingorderService.insertDiscountHouseBookingorder(discountHouseBookingorder);
            return ApiResult.success();
        }else {
            return ApiResult.error();
        }
    }

    /**
     * 折扣预约详情
     * @param id
     * @return
     */
    @GetMapping("/discount/booking/orders/{id}")
    public ApiResult discountBookingOrdersInfo(@PathVariable("id") Long id){
        DiscountHouseBookingorder discountHouseBookingorder = discountHouseBookingorderService.selectDiscountHouseBookingorderById(id);
        DiscountHouse discountHouse = discountHouseService.selectDiscountHouseById(discountHouseBookingorder.getDiscountHouseId());
        if (StringUtils.isNotEmpty(discountHouse.getTagsstr())){
            discountHouse.setTags(discountHouse.getTagsstr().split(","));
        }
        discountHouseBookingorder.setDiscountHouse(discountHouse);

        List<DiscountHouseBookingorderFollower> discountHouseBookingorderFollowers = discountHouseBookingorderFollowerService.selectDiscountHouseBookingorderFollowerList(Builder.of(DiscountHouseBookingorderFollower::new).with(DiscountHouseBookingorderFollower::setDiscountHouseBookingorderId, discountHouseBookingorder.getId()).build());
        discountHouseBookingorder.setDiscountHouseBookingorderFollowers(discountHouseBookingorderFollowers);

        List<Long> ids = discountHouseBookingorderFollowers.stream().map(item -> Long.valueOf(item.getMarketer())).distinct().collect(Collectors.toList());
        Map<Long, XcxUser> xcxUserMap = xcxUserService.getXcxUserByIds(ids);
        discountHouseBookingorderFollowers.stream().forEach(item -> {
            XcxUser xcxUser = xcxUserMap.get(Long.valueOf(item.getMarketer()));
            if (xcxUser != null){
                item.setImg(xcxUser.getAvatarUrl());
                item.setMarkName(xcxUser.getNickname());
                item.setTelphone(xcxUser.getPhone());
            }
        });
        return ApiResult.success(discountHouseBookingorder);
    }

    /**
     * 折扣跟单
     * @return
     */
    @PostMapping("/discount/booking/orders/followers")
    public ApiResult discountBookingOrdersFollowers(@RequestBody DiscountHouseBookingorderFollower discountHouseBookingorderFollower){
        if (StringUtils.isEmpty(discountHouseBookingorderFollower.getMarketer())){
            discountHouseBookingorderFollower.setMarketer(SecurityUtils.getUserId().toString());
        }
        DiscountHouseBookingorderFollower discountHouseBookingorderFollower1 = discountHouseBookingorderFollowerService.selectOneDiscountHouseBookingorderFollower(discountHouseBookingorderFollower);
        //  TODO 只能一个人接单  这个判断有问题  再说吧

        if (discountHouseBookingorderFollower1 == null){
            discountHouseBookingorderFollower1 = Builder.of(DiscountHouseBookingorderFollower::new)
                    .with(DiscountHouseBookingorderFollower::setDiscountHouseBookingorderId, discountHouseBookingorderFollower.getDiscountHouseBookingorderId())
//                    .with(ForeclosedHouseBookingorderFollower::setMarketer, SecurityUtils.getUserId().toString())
                    .with(DiscountHouseBookingorderFollower::setMarketer, discountHouseBookingorderFollower.getMarketer())
                    .with(DiscountHouseBookingorderFollower::setStage, 1)
                    .build();
            discountHouseBookingorderFollowerService.insertDiscountHouseBookingorderFollower(discountHouseBookingorderFollower1);
            DiscountHouseBookingorder discountHouseBookingorder = discountHouseBookingorderService.selectDiscountHouseBookingorderById(discountHouseBookingorderFollower.getDiscountHouseBookingorderId());
            discountHouseBookingorder.setStage(2);
            discountHouseBookingorder.setServingTime(new Date());
            discountHouseBookingorderService.updateDiscountHouseBookingorder(discountHouseBookingorder);
        }
        DiscountHouseBookingorder discountHouseBookingorder = discountHouseBookingorderService.selectDiscountHouseBookingorderById(discountHouseBookingorderFollower.getDiscountHouseBookingorderId());
        if (discountHouseBookingorder != null) {
            DiscountHouse discountHouse = discountHouseService.selectDiscountHouseById(discountHouseBookingorder.getDiscountHouseId());
            if (discountHouse != null) discountHouseBookingorder.setDiscountHouse(discountHouse);
            discountHouseBookingorderFollower1.setDiscountHouseBookingorder(discountHouseBookingorder);
            return ApiResult.success(discountHouseBookingorderFollower1);
        }
        return ApiResult.error();
    }

    /**
     * 设置备注和下一步状态更新
     * @param id
     * @param discountHouseBookingorderFollower
     * @return
     */
    @PostMapping("/discount/booking/orders/followers/{id}")
    public ApiResult discountBookingOrdersFollowersInfo(@PathVariable("id") Long id, @RequestBody DiscountHouseBookingorderFollower discountHouseBookingorderFollower){
        DiscountHouseBookingorderFollower discountHouseBookingorderFollower1 = discountHouseBookingorderFollowerService.selectDiscountHouseBookingorderFollowerById(id);
        if (discountHouseBookingorderFollower1 != null){
            if (discountHouseBookingorderFollower.getRemark() != null){
                discountHouseBookingorderFollower1.setRemark(discountHouseBookingorderFollower.getRemark());
            }
            if (discountHouseBookingorderFollower.getStage() != null){
                discountHouseBookingorderFollower1.setStage(discountHouseBookingorderFollower.getStage());
                if (discountHouseBookingorderFollower.getStage().intValue() == 2){
                    discountHouseBookingorderFollower1.setGetDemandTime(new Date());
                }
                if (discountHouseBookingorderFollower.getStage().intValue() == 3){
                    discountHouseBookingorderFollower1.setOlInviteTime(new Date());
                }

                if (discountHouseBookingorderFollower.getStage().intValue() == 4){
                    discountHouseBookingorderFollower1.setInterviewTime(new Date());
                }
                if (discountHouseBookingorderFollower.getStage().intValue() == 5){
                    discountHouseBookingorderFollower1.setBeforeSignTime(new Date());
                    DiscountHouseBookingorder discountHouseBookingorder = discountHouseBookingorderService.selectDiscountHouseBookingorderById(discountHouseBookingorderFollower1.getDiscountHouseBookingorderId());
                    discountHouseBookingorder.setStage(3);
                    discountHouseBookingorder.setFinishTime(new Date());
                    discountHouseBookingorder.setFinished(1);
                    discountHouseBookingorderService.updateDiscountHouseBookingorder(discountHouseBookingorder);
                }
            }
            DiscountHouseBookingorder discountHouseBookingorder = discountHouseBookingorderService.selectDiscountHouseBookingorderById(discountHouseBookingorderFollower1.getDiscountHouseBookingorderId());
            DiscountHouse discountHouse = discountHouseService.selectDiscountHouseById(discountHouseBookingorder.getDiscountHouseId());
            discountHouseBookingorder.setDiscountHouse(discountHouse);
            discountHouseBookingorderFollower1.setDiscountHouseBookingorder(discountHouseBookingorder);
            discountHouseBookingorderFollowerService.updateDiscountHouseBookingorderFollower(discountHouseBookingorderFollower1);
            return ApiResult.success(discountHouseBookingorderFollower1);
        }
        return ApiResult.error();
    }

    /**
     * 折扣房源批量修改状态
     * @param discountHouse
     * @return
     */
    @PostMapping("/discount/batch/update")
    public ApiResult discountBatchUpdate(@RequestBody DiscountHouse discountHouse){
        if (discountHouse.getIds() != null && discountHouse.getIds().size() > 0){
            for (Long id : discountHouse.getIds()) {
                discountHouseService.updateDiscountHouse(Builder.of(DiscountHouse::new)
                        .with(DiscountHouse::setStatus, discountHouse.getStatus())
                        .with(DiscountHouse::setId, id)
                        .build());

                if (discountHouse.getStatus().intValue() == 2){
                    // 上架
                    // TODO 如果是上架需要修改放盘签约订单进度状态
                    // TODO fo_house_uploading_order stage 改为 5
                    houseUploadingOrderService.updateHouseUploadingOrder(Builder.of(HouseUploadingOrder::new)
                            .with(HouseUploadingOrder::setStage, 5)
                            .with(HouseUploadingOrder::setId, id)
                            .build());
                }
                if (discountHouse.getStatus().intValue() == 1){
                    // 上架
                    // TODO 如果是上架需要修改放盘签约订单进度状态
                    // TODO fo_house_uploading_order stage 改为 5
                    houseUploadingOrderService.updateHouseUploadingOrder(Builder.of(HouseUploadingOrder::new)
                            .with(HouseUploadingOrder::setStage, 4)
                            .with(HouseUploadingOrder::setId, id)
                            .build());
                }
            }
            return ApiResult.success();
        }
        return ApiResult.error();
    }

    /**
     * 折扣房源批量删除
     * @param discountHouse
     * @return
     */
    @DeleteMapping("/discount/batch/destroy")
    public ApiResult discountBatchDestroy(@RequestBody DiscountHouse discountHouse){
        if (discountHouse.getIds() != null && discountHouse.getIds().size() > 0){
            for (Long id : discountHouse.getIds()) {
                discountHouseService.updateDiscountHouse(Builder.of(DiscountHouse::new)
                        .with(DiscountHouse::setDeleteTime, new Date())
                        .with(DiscountHouse::setId, id)
                        .build());
            }
            return ApiResult.success();
        }
        return ApiResult.error();
    }

    /**
     * 折扣预约生成签约订单
     * @param discountHouseSigningorder
     * @return
     */
    @PostMapping("/discount/signing/orders")
    public ApiResult discountSigningOrders(@RequestBody DiscountHouseSigningorder discountHouseSigningorder){
        DiscountHouse discountHouse = discountHouseService.selectDiscountHouseById(discountHouseSigningorder.getDiscountHouseId());
        if (discountHouse != null){
            discountHouseSigningorder.setNo(CurrencyUtil.create(10));
            discountHouseSigningorder.setClient(SecurityUtils.getUserId());
            discountHouseSigningorder.setType(2);

            discountHouseSigningorder.setMarketerJoinTime(new Date());

            // TODO 不确定对不对。。  这个是对的   此参数为市场专呗，  这里还需要添加财务经理和市场经理
            discountHouseSigningorder.setMarketer(SecurityUtils.getUserId());

            // TODO 设置财务经理 和当前用户同一个组下的财务
//            XcxUser financeXcxUser = xcxUserService.selectOneXcxUser(Builder.of(XcxUser::new)
//                    .with(XcxUser::setGroup_id, SecurityUtils.getLoginUser().getXcxUser().getGroup_id())
//                    .with(XcxUser::setActive_role_id, 3L)  // 这里传财务经理
//                    .with(XcxUser::setRole_code, "renter_finance_manager")  // 这里传财务经理
//                    .build());

            XcxUser financeXcxUser = xcxUserService.selectOneXcxUser(Builder.of(XcxUser::new)
                    .with(XcxUser::setGroup_id, SecurityUtils.getLoginUser().getXcxUser().getGroup_id())
                    .with(XcxUser::setActive_role_id, 4L)  // 这里传后勤经理  风险经理
                    .with(XcxUser::setRole_code, "renter_logistics_manager")  // 这里传后勤经理 风险经理
                    .build());
            if (financeXcxUser != null){
                discountHouseSigningorder.setFinancialManager(financeXcxUser.getId().toString());
            }
            // TODO 设置市场经理 和当前用户同一个组下的市场经理
            XcxUser marketingXcxUser = xcxUserService.selectOneXcxUser(Builder.of(XcxUser::new)
                    .with(XcxUser::setGroup_id, SecurityUtils.getLoginUser().getXcxUser().getGroup_id())
                    .with(XcxUser::setActive_role_id, 2L)  // 这里传市场经理
                    .with(XcxUser::setRole_code, "renter_marketing_manager")  // 这里传市场经理
                    .build());
            if (marketingXcxUser != null){
                discountHouseSigningorder.setMarketManager(marketingXcxUser.getId().toString());
            }

            discountHouseSigningorder.setSubmitTime(new Date());

//            foreclosedHouseSigningorder.setForeclosedHouseTitle(foreclosedHouse.getTitle());
            discountHouseSigningorderService.insertDiscountHouseSigningorder(discountHouseSigningorder);
            return ApiResult.success(discountHouseSigningorder);
        }else {
            return ApiResult.error();
        }
    }

    /**
     * 折扣签约详细
     * @return
     */
    @GetMapping("/discount/signing/orders/{id}")
    public ApiResult discountSigningOrdersInfo(@PathVariable("id") Long id){
        DiscountHouseSigningorder discountHouseSigningorder = discountHouseSigningorderService.selectDiscountHouseSigningorderById(id);
        if (discountHouseSigningorder != null){
            DiscountHouse discountHouse = discountHouseService.selectDiscountHouseById(discountHouseSigningorder.getDiscountHouseId());
            if (discountHouse != null){
                if (StringUtils.isNotEmpty(discountHouse.getTagsstr())){
                    discountHouse.setTags(discountHouse.getTagsstr().split(","));
                }
                discountHouseSigningorder.setDiscountHouse(discountHouse);
            }

            if (discountHouseSigningorder.getMarketer() != null){
                discountHouseSigningorder.setMarketerUser(xcxUserService.selectXcxUserById(discountHouseSigningorder.getMarketer()));
            }
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(discountHouseSigningorder.getFinancialManager())){
                discountHouseSigningorder.setFinancialManagerUser(xcxUserService.selectXcxUserById(Long.parseLong(discountHouseSigningorder.getFinancialManager())));
            }
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(discountHouseSigningorder.getMarketManager())){
                discountHouseSigningorder.setMarketManagerUser(xcxUserService.selectXcxUserById(Long.parseLong(discountHouseSigningorder.getMarketManager())));
            }
            return ApiResult.success(discountHouseSigningorder);
        }
        return ApiResult.error();
    }

}
